package cat.joronya.supermanager.service;

import java.io.ByteArrayOutputStream;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.htmlcleaner.ContentNode;
import org.htmlcleaner.HtmlCleaner;
import org.htmlcleaner.TagNode;

import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.util.Log;
import cat.joronya.supermanager.Supermanager;
import cat.joronya.supermanager.market.Player;
import cat.joronya.supermanager.team.Team;

/**
 * Recuperem el llistat de teams.
 * 
 * @author pol
 */
public class MyTeamsSync extends Object//AsyncTask<String,Void,Integer>
{
	private static final String TAG = "supermanager";
	
	// el service
	private SupermanagerService service;
	
	// el client http on fer les peticions
	private DefaultHttpClient client = null;
	
	// status de retorn
	public int status = -1;
	
	// teams GET
	private static final String TEAMS_LIST_GET = InitSync.BASE_URL+"/verequipos.php";
	// team detail
	private static final String TEAM_DETAIL_GET = InitSync.BASE_URL+"/verequipo.php";
	
	// XPATHs per treure dades de les pagines
	// teams XPATH
	private static final String TEAMS_XPATH = "//td[@background='gif/tusequipos2.gif']";
	// jornada XPATH
	private static final String TEAMS_DAY_XPATH = "//td[@class='gris']";
	// team cash XPATH
	private static final String TEAM_CASH_XPATH = "//td[@background='gif/tablaarribanegro2.gif']";
	// team players XPATH
	private static final String TEAM_PLAYERS_XPATH = "//td[@class='titulonegroi']";
	// team extra details javascript XPATH
	private static final String TEAM_JAVASCRIPT_XPATH = "//script[@language='JavaScript']";
	
	// dades extretes de les pagines
	public ArrayList<Team> teams;
	
	/**
	 * Constructor amb el intentService que el crida.
	 * @param intentService
	 */
	public MyTeamsSync(SupermanagerService service, DefaultHttpClient client)
	{
		this.service = service;
		this.client = client;
	}
	
	@SuppressWarnings("rawtypes")
	protected void execute()//doInBackground(String... params) 
	{
		try
		{
			// checkejem per connectivitat
			ConnectivityManager cm = (ConnectivityManager) service.getSystemService(Context.CONNECTIVITY_SERVICE);
			boolean online = cm.getActiveNetworkInfo().isConnectedOrConnecting();
			
			if( !online )
				throw new ConnectivityException();
			
			// empty array of private leagues
			teams = new ArrayList<Team>();
			
			HttpGet plHttpGet = new HttpGet(TEAMS_LIST_GET);
			HttpResponse response = client.execute(plHttpGet);
			HtmlCleaner cleaner = new HtmlCleaner();
			
			ByteArrayOutputStream os = new ByteArrayOutputStream();
	        response.getEntity().writeTo(os);
	        String teamsPage = os.toString(HTTP.ISO_8859_1);
	        TagNode node = cleaner.clean(teamsPage);
			
	        NumberFormat nf = NumberFormat.getInstance(new Locale("es","ES"));
	        
			// cerquem els equips
	        Object[] tdTeam = node.evaluateXPath(TEAMS_XPATH);
	        TagNode tagTeamHeader = (TagNode)tdTeam[0];
	        TagNode tagTeamTable = tagTeamHeader.getParent().getParent();
	        
	        // llistem els equips, diferents trs
	        for(Object objTr: tagTeamTable.getChildren())
	        {
	        	// els tds
	        	List tds = ((TagNode)objTr).getChildren();
	        	
	        	// primer td
	       		TagNode td0 = (TagNode)tds.toArray()[0];
	       		
	       		// si es el primer acabem, es a dir te background='gif/tusequipos2.gif'
	       		if( "gif/tusequipos2.gif".equals(td0.getAttributeByName("background")) )
	       			continue;
	       		
	       		// si es l'ultim acabem, es a dir te background='gif/tusequiposabajo2.gif'
	       		if( "gif/tusequiposabajo2.gif".equals(td0.getAttributeByName("background")) )
	       			continue;
	       		
	       		// segon td
	       		TagNode td1 = (TagNode)tds.toArray()[1];
	       		
	       		// agafem fills a veure si es equip
	       		List td1Childs = td1.getChildren();
	       		
	       		// tr de titols pq td1 amb un fill, el br i no img i anchor
	       		if( td1Childs.size() == 1 )
	       			continue;
	       		
	       		TagNode td1ChildsChild1 = (TagNode)td1Childs.toArray()[1];

	       		// inicialitzem team
	        	Team team = new Team();
	        	// cerquem nom de l'equip
	        	if( "a".equals(td1ChildsChild1.getName()) )
	       		{
	       			String href = td1ChildsChild1.getAttributeByName("href");
	       			String id_equ = href.replaceFirst("verequipo.php.id_equ=", "");
	       			team.setIdEqu(id_equ);
	       			for( Object aContent: td1ChildsChild1.getChildren() )
	       			{
	       				if( aContent instanceof ContentNode )
	       					team.setName(aContent.toString());
	       			}
	       		}
	        	
	        	// tercer td
	        	TagNode td2 = (TagNode)tds.toArray()[2];
	        	for( Object td2Child: td2.getChildren() )
	        	{
	        		if( td2Child instanceof ContentNode )
	        		{
	        			Float points = Float.valueOf("0");
	       				Integer pointsClass = Integer.valueOf(0);
	       				Pattern p = Pattern.compile("([^\\s]*)\\s\\(([^\\º]*)º\\)");
	       				Matcher m = p.matcher(td2Child.toString());
	       				if( m.find() ) 
	       				{
	       					try{
	           					points = Float.valueOf(nf.parse(m.group(1)).floatValue());
	           				}catch(ParseException pe){
	           					points = Float.valueOf("0");
	           				}
	           				try{
	           					pointsClass = Integer.valueOf(nf.parse(m.group(2)).intValue());
	           				}catch(ParseException pe){
	           					pointsClass = Integer.valueOf("0");
	           				}
	       				}
	       				team.setPoints(points);
	       				team.setPointsClassification(pointsClass);
	        		}
	        	}
	        	
	        	// quart td
	        	TagNode td3 = (TagNode)tds.toArray()[3];
	        	for( Object td3Child: td3.getChildren() )
	        	{
	        		if( td3Child instanceof ContentNode )
	        		{
	        			Float general = Float.valueOf("0");
	       				Integer generalClass = Integer.valueOf(0);
	       				Pattern p = Pattern.compile("([^\\s]*)\\s\\(([^º]*)º\\)");
	       				Matcher m = p.matcher(td3Child.toString());
	       				if( m.find() ) 
	       				{
	       					try{
	       						general = Float.valueOf(nf.parse(m.group(1)).floatValue());
	           				}catch(ParseException pe){
	           					general = Float.valueOf("0");
	           				}
	           				try{
	           					generalClass = Integer.valueOf(nf.parse(m.group(2)).intValue());
	           				}catch(ParseException pe){
	           					generalClass = Integer.valueOf("0");
	           				}
	       				}
	       				team.setGeneral(general);
	       				team.setGeneralClassification(generalClass);
	        		}
	        	}
	        	
	        	// cinque td
	        	TagNode td4 = (TagNode)tds.toArray()[4];
	        	for( Object td4Child: td4.getChildren() )
	        	{
	        		if( td4Child instanceof ContentNode )
	        		{
	        			Integer broker = Integer.valueOf("0");
	       				Integer brokerClass = Integer.valueOf(0);
	       				Pattern p = Pattern.compile("([^\\s]*)\\s*\\(([^º]*)º\\)");
	       				Matcher m = p.matcher(td4Child.toString());
	       				if( m.find() ) 
	       				{
	       					try{
	       						broker = Integer.valueOf(nf.parse(m.group(1)).intValue());
	           				}catch(ParseException pe){
	           					broker = Integer.valueOf("0");
	           				}
	           				try{
	           					brokerClass = Integer.valueOf(nf.parse(m.group(2)).intValue());
	           				}catch(ParseException pe){
	           					brokerClass = Integer.valueOf("0");
	           				}
	       				}
	       				team.setBroker(broker);
	       				team.setBrokerClassification(brokerClass);
	        		}
	        	}
	        	
	        	// passar la jornada i guardar-la
		        Object[] tdJornada = node.evaluateXPath(TEAMS_DAY_XPATH);
		        for( Object jornadaContent: ((TagNode)tdJornada[1]).getChildren() )
		        {
		        	Integer day = Integer.valueOf("0");
					try{
						day = Integer.valueOf(nf.parse(jornadaContent.toString().replace("Jornada ","").trim()).intValue());
	   				}catch(ParseException pe){
	   					day = Integer.valueOf("0");
	   				}
		        	team.setDay(day);
		        }
	        	
	        	// guardem al llistat de teams
        		teams.add(team);
	        }
	        
	        // de cada team parsejem el detall
	        for(Team t: teams)
	        {
	        	getTeamDetail(t);
	        }
	        
	        // parsejat ok
	        status = Supermanager.MY_TEAMS_PARSED_OK;
	        Log.d(TAG, "MArketSync status: MY_TEAMS_PARSED_OK - "+status);
	        return;
		}
		catch(ConnectivityException ce){
			// error de connectivitat
			status = Supermanager.CONNECTIVITY_ERROR_STATUS;
	        Log.d(TAG, "MArketSync status: CONNECTIVITY_ERROR_STATUS - "+status);
			return;
		}
		catch(Exception e){
			// altre error, notifiquem i anem offline
			status = Supermanager.OTHER_ERROR_STATUS;
	        Log.d(TAG, "MArketSync status: OTHER_ERROR_STATUS - "+status);
			return;
		}
    }
	
	@SuppressWarnings("rawtypes")
	protected void getTeamDetail(Team team) 
		throws Exception
	{
		HttpGet plHttpGet = new HttpGet(TEAM_DETAIL_GET+"?id_equ="+team.getIdEqu());
		HttpResponse response = client.execute(plHttpGet);
		HtmlCleaner cleaner = new HtmlCleaner();
		
		ByteArrayOutputStream os = new ByteArrayOutputStream();
        response.getEntity().writeTo(os);
        String teamPage = os.toString(HTTP.ISO_8859_1);
        TagNode node = cleaner.clean(teamPage);
		
        NumberFormat nf = NumberFormat.getInstance(new Locale("es","ES"));
        
		// cerquem el cash
        Object[] tdsCash = node.evaluateXPath(TEAM_CASH_XPATH);
        TagNode cashTd = (TagNode)tdsCash[1];
        for( Object cashContent: cashTd.getChildren() )
		{
			if( cashContent instanceof ContentNode )
			{
				Integer cash = Integer.valueOf("0");
				try{
					cash = Integer.valueOf(nf.parse(cashContent.toString().trim()).intValue());
   				}catch(ParseException pe){
   					cash = Integer.valueOf("0");
   				}
				team.setCash(cash);
			}
		}
        
        // llistat de jugadors
        Object[] tdHeaderPlayers = node.evaluateXPath(TEAM_PLAYERS_XPATH);
        TagNode[] trsPlayers = ((TagNode)tdHeaderPlayers[0]).getParent().getParent().getChildTags();
        int position = -1;
        for( TagNode trPlayer: trsPlayers )
        {
        	position++;
        	TagNode[] tds = trPlayer.getChildTags();
        	
        	// td0, saltem el primer tr dels titular
        	if( "titulonegroi".equals(tds[0].getAttributeByName("class")) )
        		continue;
        	
        	// saltem l'ultim tr del peu
        	if( "gif/fondotablaabajoizquierdaarriba.gif".equals(tds[0].getAttributeByName("background")) )
        		continue;
        	
        	// mirem el rowspan
        	int rowspan = ("3".equals(tds[0].getAttributeByName("rowspan")) 
        			|| "4".equals(tds[0].getAttributeByName("rowspan")))?1:0;
        	
        	// inicialitzem jugador
        	Player player = new Player();
        	player.setDay(team.getDay());
        	player.setNumPosition(position);
        	
        	// td1, status: nacional/estranger o lesionat/out
        	try{
        		TagNode imgStatus = tds[1+rowspan].getChildTags()[0];
        		if( "gif/nacional.gif".equals(imgStatus.getAttributeByName("src")) )
        			player.setNacionality("nacional.png");
        		if( "gif/extra.gif".equals(imgStatus.getAttributeByName("src")) )
        			player.setNacionality("extra.png");
        	}catch(Exception e){}
        	
        	// td2, jugador
        	try{
        		TagNode jugador = tds[2+rowspan].getChildTags()[0];
        		if( "a".equals(jugador.getName()) )
        		{
        			String codi = jugador.getAttributeByName("href").
        				replace("http://www.acb.com/stspartidojug.php?cod_jugador=", "");
        			player.setId(codi);
        		}
        	}catch(Exception e){}
        	
        	// td4, equip
        	try{
        		List equipChild = tds[4+rowspan].getChildren();
        		for( Object equipContent: equipChild )
        		{
        			if( equipContent instanceof ContentNode )
        			{
        				player.setTeam(equipContent.toString().trim());
        			}
        		}
        	}catch(Exception e){}
        	
        	// td5, cost fitxatge i jornada del fitxatge
        	try{
        		List costChild = tds[5+rowspan].getChildren();
        		for( Object costContent: costChild )
        		{
        			if( costContent instanceof ContentNode )
        			{
        				Integer cost = Integer.valueOf(0);
	       				Integer buyDay = Integer.valueOf(1);
	       				Pattern p = Pattern.compile("([^\\s]*)\\s*\\(j&ordf;([^\\)]*)\\)");
	       				Matcher m = p.matcher(costContent.toString().trim());
	       				if( m.find() ) 
	       				{
	       					try{
	       						cost = Integer.valueOf(nf.parse(m.group(1)).intValue());
	           				}catch(ParseException pe){
	           					cost = Integer.valueOf(0);
	           				}
	           				try{
	           					buyDay = Integer.valueOf(nf.parse(m.group(2)).intValue());
	           				}catch(ParseException pe){
	           					buyDay = Integer.valueOf(1);
	           				}
	       				}
	       				player.setCost(cost);
	       				player.setBuyDay(buyDay);
        			}
        		}
        	}catch(Exception e){}

        	// td6, actual price
        	try{
        		List priceChild = tds[6+rowspan].getChildren();
        		for( Object priceContent: priceChild )
        		{
        			if( priceContent instanceof ContentNode )
        			{
        				Integer cost = Integer.valueOf(0);
        				try{
       						cost = Integer.valueOf(nf.parse(priceContent.toString()).intValue());
           				}catch(ParseException pe){
           					cost = Integer.valueOf(0);
           				}
        				player.setPrice(cost);
        			}
        		}
        	}catch(Exception e){}

        	// td7, actual price
        	try{
        		List ratingChild = tds[7+rowspan].getChildren();
        		for( Object ratingContent: ratingChild )
        		{
        			if( ratingContent instanceof ContentNode )
        			{
        				Float rating = Float.valueOf(0);
        				try{
        					rating = Float.valueOf(nf.parse(ratingContent.toString()).floatValue());
           				}catch(ParseException pe){
           					rating = Float.valueOf(0);
           				}
        				player.setRating(rating);
        			}
        		}
        	}catch(Exception e){}
        	
        	// td8, victory
        	try{
        		TagNode[] victoryChild = tds[8+rowspan].getChildTags();
        		for( TagNode victoryTag: victoryChild )
        		{
        			if( "font".equals(victoryTag.getName()) )
        				player.setVictory(true);
        		}
        	}catch(Exception e){}
        
        	// td9, average rating
        	try{
        		List averageRatingChild = tds[9+rowspan].getChildren();
        		for( Object averageRatingContent: averageRatingChild )
        		{
        			if( averageRatingContent instanceof ContentNode )
        			{
        				Float averageRating = Float.valueOf(0);
        				try{
        					averageRating = Float.valueOf(nf.parse(averageRatingContent.toString()).floatValue());
           				}catch(ParseException pe){
           					averageRating = Float.valueOf(0);
           				}
        				player.setAverageRating(averageRating);
        			}
        		}
        	}catch(Exception e){}
        	
        	// afegim el player a l'equip
        	team.addPlayer(position,player);
        }
        
        // cerquem javascript amb altres dades
        try
        {
        	Object[] tdsJS = node.evaluateXPath(TEAM_JAVASCRIPT_XPATH);
        	TagNode valsTd = (TagNode)tdsJS[2];
        	for( Object valsJSContent: valsTd.getChildren() )
        	{
        		if( valsJSContent instanceof ContentNode )
        		{
        			String[] vals = valsJSContent.toString().split("\n");
        			int tipus = 0;
        			for(String val: vals)
        			{
        				// saltem linies buides
        				if( "".equals(val.trim()) )
        					continue;
        				
        				// saltem linia function
        				if( "function muestra(valor)".equals(val.trim()) )
        					continue;
        				
        				// linies amb claus del javascript
        				if( "{".equals(val.trim()) || "}".equals(val.trim()) )
        					continue;
        				
        				// canvi de seccio de javascript
        				Pattern p = Pattern.compile("if \\(valor=='([^']*)'\\)");
	       				Matcher m = p.matcher(val.trim());
	       				if( m.find() ) 
	       				{
	       					if( "puntos".equals(m.group(1)) )
	       						tipus = 1;
	       					else if( "rebotes".equals(m.group(1)) )
	       						tipus = 2;
	       					else if( "triples".equals(m.group(1)) )
	       						tipus = 3;
	       					else if( "asistencias".equals(m.group(1)) )
	       						tipus = 4;
	       					
	       					// continuem a la seguent linia
	       					continue;
	       				}
	       				
	       				// exteiem els valors pel tipus en la posisio
	       				Pattern p2 = Pattern.compile("document.getElementById\\('val([^']*)'\\).innerHTML='([^']*)';document.getElementById\\('media([^']*)'\\).innerHTML='([^']*)';");
	       				Matcher m2 = p2.matcher(val.trim());
	       				if( m2.find() ) 
	       				{
	       					int pos = 0;
	        				try{
	        					pos = nf.parse(m2.group(1)).intValue();
	           				}catch(ParseException pe){
	           					pos = 0;
	           				}
	           				
	           				Integer value = Integer.valueOf(0);
	        				try{
	       						value = Integer.valueOf(nf.parse(m2.group(2)).intValue());
	           				}catch(ParseException pe){
	           					value = Integer.valueOf(0);
	           				}
	           				
           					Float average = Float.valueOf(0);
            				try{
            					average = Float.valueOf(nf.parse(m2.group(4)).floatValue());
               				}catch(ParseException pe){
               					average = Float.valueOf(0);
               				}
               				
               				switch(tipus)
               				{
               				case 1:
               					team.setPointsToPosition(value,average,pos);
               					break;
               				case 2:
               					team.setReboundsToPosition(value,average,pos);
               					break;
               				case 3:
               					team.setThreeToPosition(value,average,pos);
               					break;
               				case 4:
               					team.setAssistencesToPosition(value,average,pos);
               					break;
               				}
	       				}	
        			}
        			
        		}
        	}
        }catch(Exception e){}
        
        // TODO: recuperar earnings i altres dades necessaries
	}

	/**
	 * Guardar les dades trobades a DB.
	 */
    protected void onPostExecute(Uri uri) 
    {
    	// tractem cada team
    	Log.d(TAG,"Parsed "+teams.size()+" teams, going to insert/update");
    	for(Team team: teams)
    	{
    		// insert or update la private league
			String lastPathSegment = insertOrUpdateTeam(uri, team);
			
    		// equip sense jugadors
    		if( team.getPlayers() == null )
    		{
    			Log.d(TAG,"Team ["+team.getName()+"] has no players");
    			continue;
    		}
    		
    		// guardem els jugadors
    		for(Player player: team.getPlayers().values())
    		{
    			// insert or update team player
    			insertOrUpdateMyTeamPlayer(lastPathSegment, team, player);
    		}
    	}
    }
    
    /**
	 * Insert or Update Team as needed.
	 * @param uri
	 * @param pl
	 * @return
	 */
	private String insertOrUpdateTeam(Uri uri, Team team)
	{
		// insertem el team
		ContentValues values = new ContentValues();
		values.put(Supermanager.MyTeam.ID_EQU, team.getIdEqu());
		values.put(Supermanager.MyTeam.DAY, team.getDay());
		values.put(Supermanager.MyTeam.NAME, team.getName());
		values.put(Supermanager.MyTeam.POINTS, team.getPoints());
		values.put(Supermanager.MyTeam.GENERAL, team.getGeneral());
		values.put(Supermanager.MyTeam.BROKER, team.getBroker());
		values.put(Supermanager.MyTeam.POINTS_CLASSIFICATION, team.getPointsClassification());
		values.put(Supermanager.MyTeam.GENERAL_CLASSIFICATION, team.getGeneralClassification());
		values.put(Supermanager.MyTeam.BROKER_CLASSIFICATION, team.getBrokerClassification());
		values.put(Supermanager.MyTeam.POINTS_BEST, team.getPointsBest());
		values.put(Supermanager.MyTeam.GENERAL_BEST, team.getGeneralBest());
		values.put(Supermanager.MyTeam.POINTS_AVERAGE, team.getPointsAverage());
		values.put(Supermanager.MyTeam.BEST_CLASSIFICATION, team.getBestClassification());
		values.put(Supermanager.MyTeam.CASH, team.getCash());
		values.put(Supermanager.MyTeam.EARNINGS, team.getEarnings());
		values.put(Supermanager.MyTeam.AVERAGE_SEASON, team.getAverageSeason());
		values.put(Supermanager.MyTeam.AVERAGE_VARIATION, team.getAverageVariation());
		
		Uri teamUri = Supermanager.MyTeam.CONTENT_URI;
		String lastPathSegment = "0";
		
		// si update no retorna 1 reg, llavors insert
		if( service.getContentResolver().update(uri, 
				values, 
				Supermanager.MyTeam.ID_EQU+" = ? AND "+
				Supermanager.MyTeam.DAY+" = ? ", 
				new String[]{team.getIdEqu(), team.getDay().toString()}) == 0 )
		{
			teamUri = service.getContentResolver().insert(uri, values);
			lastPathSegment = teamUri.getLastPathSegment();
			Log.d(TAG, "Inserting team [" + team.getName()
					+ "] with Uri [" + teamUri + "] lastPathSegment ["
					+ lastPathSegment + "]");
		}
		else
		{
			Cursor cursor = service.getContentResolver().
				query(Supermanager.MyTeam.CONTENT_URI, 
					  Supermanager.MyTeam.PROJECTION, 
					  Supermanager.MyTeam.ID_EQU+" = ? AND "+
					  Supermanager.MyTeam.DAY+" = ? ", 
					  new String[]{team.getIdEqu(), team.getDay().toString()}, 
					  Supermanager.MyTeam.DEFAULT_SORT_ORDER);
			
			if( cursor.moveToFirst() )
			{
				lastPathSegment = ""+cursor.getLong(0);
				teamUri = ContentUris.withAppendedId(Supermanager.MyTeam.CONTENT_URI, cursor.getLong(0));
			}
			Log.d(TAG, "Updating team [" + team.getName()
					+ "] with Uri [" + teamUri + "] lastPathSegment ["
					+ lastPathSegment + "]");
		}
		
		return lastPathSegment;
	}
	
	public Uri insertOrUpdateMyTeamPlayer(String lastPathSegment, Team team, Player player)
	{
		// insertem el team
		ContentValues vplayer = new ContentValues();
		vplayer.put(Supermanager.MyTeamDetail.ID_EQU, team.getIdEqu());
		vplayer.put(Supermanager.MyTeamDetail.DAY, team.getDay());
		vplayer.put(Supermanager.MyTeamDetail.POSITION, player.getNumPosition());
		vplayer.put(Supermanager.MyTeamDetail.ID_PLAYER, player.getId());
		vplayer.put(Supermanager.MyTeamDetail.COST, player.getCost());
		vplayer.put(Supermanager.MyTeamDetail.SIGNING_DAY, player.getBuyDay());
		vplayer.put(Supermanager.MyTeamDetail.PRICE, player.getPrice());
		vplayer.put(Supermanager.MyTeamDetail.WIN, player.isVictory()?1:0);
		vplayer.put(Supermanager.MyTeamDetail.RATING, player.getRating());
		vplayer.put(Supermanager.MyTeamDetail.POINTS, player.getPoints());
		vplayer.put(Supermanager.MyTeamDetail.REBOUNDS, player.getRebounds());
		vplayer.put(Supermanager.MyTeamDetail.THREE, player.getThree());
		vplayer.put(Supermanager.MyTeamDetail.ASSISTS, player.getAssistences());
		vplayer.put(Supermanager.MyTeamDetail.RATING_AVERAGE, player.getAverageRating());
		vplayer.put(Supermanager.MyTeamDetail.POINTS_AVERAGE, player.getAveragePoints());
		vplayer.put(Supermanager.MyTeamDetail.REBOUNDS_AVERAGE, player.getAverageRebounds());
		vplayer.put(Supermanager.MyTeamDetail.THREE_AVERAGE, player.getAverageThree());
		vplayer.put(Supermanager.MyTeamDetail.ASSISTS_AVERAGE, player.getAverageAssistences());
		
		Uri pUri = Supermanager.MyTeamDetail.CONTENT_URI;
		// si update no retorna 1 reg, llavors insert
		if( service.getContentResolver().update(Supermanager.MyTeamDetail.CONTENT_URI, 
				vplayer, 
				Supermanager.MyTeamDetail.ID_EQU+" = ? AND "+
				Supermanager.MyTeamDetail.ID_PLAYER+" = ? AND "+
				Supermanager.MyTeamDetail.DAY+" = ? AND "+
				Supermanager.MyTeamDetail.POSITION+" = ? ", 
				new String[]{
					team.getIdEqu(), 
					player.getId(), 
					team.getDay().toString(), 
					player.getNumPosition().toString()
				}) == 0 )
		{
			pUri = service.getContentResolver().insert(
					Supermanager.MyTeamDetail.CONTENT_URI, vplayer);
			Log.d(TAG, "Inserting player [" + player.getName() + "] of team ["
					+ team.getName() + "] with Uri [" + pUri + "]");
		}
		else
		{
			Cursor cursor = service.getContentResolver().
			query(Supermanager.MyTeamDetail.CONTENT_URI, 
				  Supermanager.MyTeamDetail.PROJECTION, 
				  Supermanager.MyTeamDetail.ID_EQU+" = ? AND "+
				  Supermanager.MyTeamDetail.ID_PLAYER+" = ? AND "+
				  Supermanager.MyTeamDetail.DAY+" = ? AND "+
				  Supermanager.MyTeamDetail.POSITION+" = ? ", 
				  new String[]{
					team.getIdEqu(), 
					player.getId(),
					team.getDay().toString(),
					player.getNumPosition().toString()
				  }, 
				  Supermanager.MyTeamDetail.DEFAULT_SORT_ORDER);
		
			if( cursor.moveToFirst() )
			{
				pUri = ContentUris.withAppendedId(Supermanager.MyTeamDetail.CONTENT_URI, cursor.getLong(0));
		
				Log.d(TAG, "Updating player [" + player.getName() + "] of team ["
						+ team.getName() + "] with Uri [" + pUri + "]");
			}
		}
		return pUri;
	}
}	
